package com.kksoft.android.xiaoliaobaike.fetcher.thread;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.tsz.afinal.FinalHttp;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;

import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.util.Log;

import com.kksoft.android.xiaoliaobaike.Const;
import com.kksoft.android.xiaoliaobaike.model.FetchTask;
import com.kksoft.android.xiaoliaobaike.model.Series;

public class FetchSeriesThread implements Runnable {

	private static final String TAG = "FetchPageThread";

	private FetchTask task;

	protected Handler seriesHandler;

	public FetchSeriesThread(Handler seriesHandler, FetchTask task) {
		this.seriesHandler = seriesHandler;
		this.task = task;
	}

	public void run() {
		Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

		List<Series> allSeriesList = new ArrayList<Series>();

		String url = task.getUrl();

		// 获取数据
		sendMessage(Const.MSG_SERIES_FETCH_START);

		String pageContent = null;
		try {
			pageContent = FinalHttp.get(url);
			if (pageContent == null || pageContent == "" || pageContent.length() == 0) {
				Log.w(TAG, "url not found : " + url);
				sendMessage(Const.MSG_URL_NOT_FOUND, "url not found : " + url);

				return;
			}
		} catch (Exception e) {
			Log.e(TAG, e.getMessage(), e);
			sendMessage(Const.MSG_SERIES_FETCH_ERROR, e.getMessage());
			return;
		}

		sendMessage(Const.MSG_SERIES_FETCH_FINISH);

		// 解析数据
		sendMessage(Const.MSG_SERIES_ANALYSIS_START);

		List<Series> seriesList = null;

		try {
			seriesList = parsePage(pageContent);
		} catch (Exception e) {
			Log.e(TAG, e.getMessage(), e);
			sendMessage(Const.MSG_SERIES_ANALYSIS_ERROR, e.getMessage());
			return;
		}

		allSeriesList.addAll(seriesList);

		sendMessage(Const.MSG_SERIES_ANALYSIS_FINISH);

		sendMessage(Const.MSG_SERIES_LIST, allSeriesList);
	}

	private void sendMessage(int what) {
		sendMessage(what, null);
	}

	private void sendMessage(int what, Object obj) {
		Message toSend = seriesHandler.obtainMessage(what);
		toSend.arg1 = task.getId();
		toSend.arg2 = task.getPage();
		toSend.obj = obj;
		seriesHandler.sendMessage(toSend);
	}

	/**
	 * 获得页码范围
	 * 
	 * @return [pageStart, pageEnd]
	 */
	protected int[] fetchPageRange() {

		int pageStart = 0;
		int pageEnd = 0;

		try {
			String url = Const.getSeriesListUrl(Integer.MAX_VALUE);
			String pageContent = FinalHttp.get(url);
			Document doc = Parser.parse(pageContent, Const.BASE_URL);

			Elements pagebar = doc.getElementsByClass("pagebar");
			if (pagebar != null && pagebar.size() > 0) {
				Elements pageList = doc.getElementsByClass("pagebar").get(0).getElementsByTag("a");

				for (int i = 0; i < pageList.size(); i++) {
					String text = pageList.get(i).ownText();

					if (text != null && text.trim().length() > 0) {
						try {
							pageStart = Integer.parseInt(text);
							break;
						} catch (NumberFormatException e) {
							e.printStackTrace();
						}
					}
				}
				for (int i = pageList.size() - 1; i >= 0; i--) {
					String text = pageList.get(i).ownText();

					if (text != null && text.trim().length() > 0) {
						try {
							pageEnd = Integer.parseInt(text);
							break;
						} catch (NumberFormatException e) {
							e.printStackTrace();
						}
					}
				}
			} else {
				pageStart = 1;
				pageEnd = 1;
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "err:" + e.getMessage());
		}
		return new int[] { pageStart, pageEnd };
	}

	/**
	 * 解析series页面数据
	 * 
	 * @param html
	 * @return
	 */
	private List<Series> parsePage(String html) {
		List<Series> seriesList = new ArrayList<Series>(12);

		try {
			// Document parse = Jsoup.parse(html);
			Document parse = Parser.parse(html, Const.BASE_URL);

			Element seriesDivList = parse.getElementsByClass("series-list").get(0);

			Iterator<Element> seriesCf = seriesDivList.children().iterator();

			while (seriesCf.hasNext()) {
				analize(seriesList, seriesCf);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return seriesList;
	}

	/**
	 * 解析每个series
	 * 
	 * @param seriesList
	 * @param seriesCf
	 */
	private void analize(List<Series> seriesList, Iterator<Element> seriesCf) {
		Element next = seriesCf.next();
		Element seriesDescribe = next.getElementsByClass("series-describe").get(0);
		Element title = seriesDescribe.getElementsByIndexEquals(0).get(0).child(0).child(0);

		String seriesUrl = title.absUrl("href");
		String titleStr = title.ownText();

		Integer seriesId = null;

		if (seriesUrl != null && seriesUrl.length() > 0) {
			if (seriesUrl.lastIndexOf('/') != -1)
				;
			{
				try {
					seriesId = Integer.parseInt(seriesUrl.substring(seriesUrl.lastIndexOf('/') + 1));
				} catch (Exception e) {
					e.printStackTrace();
					Log.e(TAG, e.getMessage(), e);
				}
			}
		}

		String coverUrl = seriesDescribe.getElementsByTag("img").get(0).absUrl("src");

		String describe = seriesDescribe.getElementsByIndexEquals(2).get(0).text();

		Element moreDescribe = next.getElementsByClass("more-describe").get(0);

		int total = 0;
		try {
			total = Integer.parseInt(moreDescribe.text().replace("共", "").replace("话", ""));
		} catch (Exception e) {
			e.printStackTrace();
			Log.w(TAG, "解析series total话出错");
		}

		Element firstUrlA = moreDescribe.getElementsByClass("button").get(0);
		String firstUrl = firstUrlA.absUrl("href");

		seriesList.add(new Series(null, seriesId, titleStr, seriesUrl, coverUrl, describe, total, firstUrl, 0, 0));
	}

}